package com.itheima.user.controller;


import com.itheima.sh.entity.OrderEntity;
import com.itheima.sh.entity.UserEntity;
import com.itheima.sh.feign.OrderFeign;
import com.itheima.sh.vo.request.AddOrderVO;
import com.itheima.sh.vo.response.OrderResultVO;
import com.itheima.sh.vo.response.ResultVO;
import com.itheima.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    DiscoveryClient discoveryClient;
    @Autowired
    private OrderFeign orderFeign; //基于JDK动态代理，获取到url 发起远程调用， 动态代理对象存到 IOC容器

    //用户登录
    @GetMapping("/login/{userName}/{password}")
    public ResultVO login(@PathVariable("userName") String userName, @PathVariable("password") String password) {
        boolean loginResult = userService.login(userName, password);
        ResultVO result = new ResultVO();
        if (loginResult) {
            result.setSuccess(true);
        } else {
            result.setSuccess(false);
        }
        return result;
    }

    //查询用户订单信息
    @GetMapping("/findUserOrders/{userId}")
    public OrderResultVO findUserOrders(@PathVariable("userId") Integer userId, HttpServletRequest request) {

        UserEntity userEntity = userService.findUserById(userId);
        /* 1.IP和端口硬编码问题
           2.服务请求路径硬编码问题
           3.存在高并发不可用问题，不能负载均衡调用服务的提供方
        * */

        //todo
        /*用代码发送http请求
        String url = "http://localhost:9001/order/findOrderInfoByUserId/" + userId;
        List list = restTemplate.getForObject(url, List.class);
        OrderResultVO orderResultVO = OrderResultVO.builder().userName(userEntity.getUserName()).orderList(list).build();
        return orderResultVO;*/


        /*//1.解决IP和端口号硬编码问题 注册中心根据order-service拉取服务对应的IP和对应的端口PORT
        List<ServiceInstance> instances = discoveryClient.getInstances("order-service");
        ServiceInstance serviceInstance = instances.get(0);//服务实例化对象
        String host = serviceInstance.getHost();//IP
        int port = serviceInstance.getPort();//端口
        String url="http://"+host+":"+port+"/order/findOrderInfoByUserId/"+userId;

//        //3.解决：存在高并发不可用问题，不能负载均衡调用服务的提供方*/
//        //负载均衡算法默认是轮询
//        String url="http://order-service/order/findOrderInfoByUserId/"+userId;
//        //发起远程调用
//        List list = restTemplate.getForObject(url, List.class);
//        OrderResultVO orderResultVO = OrderResultVO.builder()
//                                                    .userName(userEntity.getUserName())
//                                                    .orderList(list).build();
//
        //2.解决服务请求路径硬编码问题,用Feign完成远程调用
        List<OrderEntity> list = orderFeign.findOrderInfoByUserId(userId);
        OrderResultVO orderResultVO = OrderResultVO.builder()
                                                   .userName(userEntity.getUserName())
                                                   .orderList(list)
                                                   .build();
        String company = request.getHeader("company");
        System.out.println(company);
        return orderResultVO;
    }

    //添加订单
    @PostMapping("/addUserOrder")
    public ResultVO addUserOrder(@RequestBody AddOrderVO addOrderVO) {
        ResultVO result = new ResultVO();
        //判断用户是否存在
        UserEntity userEntity = userService.findUserById(addOrderVO.getUserId());
        if (userEntity == null) {
            result.setSuccess(false);
            return result;
        }

        //todo

        return result;
    }
}
